package com.eques.service

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Notification
import android.app.Service
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Bitmap
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import com.eques.event.EventTotalThread
import com.eques.icvss.api.ICVSSUserInstance
import com.eques.icvss.utils.ELog
import com.eques.icvss.utils.ResultCode
import com.eques.impl.ImgDataListener
import com.eques.iot.api.IOTListener
import com.eques.util.AppUtils
import com.eques.util.AppUtils.context
import com.eques.util.AppUtils.service
import com.eques.util.Config
import com.eques.util.EquesMytool
import com.eques.util.EquesPreference
import com.eques.util.HttpsUtils
import com.eques.util.ICVSSUserModule.Companion.getInstance
import com.eques.util.NetConnctioUtils.isNetworkConnected
import com.eques.util.StringUtils
import com.eques.util.StringUtils.isBlank
import org.greenrobot.eventbus.EventBus
import java.lang.ref.WeakReference
import java.time.Instant
import java.time.ZoneId
import java.util.Locale
import java.util.concurrent.Executors
import kotlin.concurrent.Volatile

class DoorBellService : Service() {
    private var mContext: Context? = null
    private var equesPres: EquesPreference? = null
    private var messageResponse: ServerMessageResponse? = null


    private val mHandler = MyHandler(WeakReference(this))

    inner class MyHandler(val wrActivity: WeakReference<DoorBellService>) :
        Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val doorBellService = wrActivity.get()
            if (doorBellService != null) {
                when (msg.what) {
                    MSG_DO_LOGIN ->                         // 主动登录
                        doorBellService.loginScene(MSG_DO_LOGIN)

                    MSG_AUTO_LOGIN ->                         // 自动登录
                        doorBellService.loginScene(MSG_AUTO_LOGIN)

                    MSG_ONCLICK_LOGIN ->                         // 点击重连
                        doorBellService.loginScene(MSG_ONCLICK_LOGIN)

                    else -> {}
                }
            } else {
                ELog.d(TAG, " DoorBellService-->activity is null... ")
            }
            super.handleMessage(msg)
        }
    }


    override fun onCreate() {
        super.onCreate()
        mContext = context
        equesPres = EquesPreference(mContext!!)
        service = this
        initIcvss()
        isClickReconnection = false
    }

    /**
     * 检查登录前状态
     *
     * @return
     */
    fun loginCheck(): Boolean {
        if (mContext == null) {
            mContext = context
            if (mContext == null) {
                return false
            }
        }
        val network = isNetworkConnected(mContext!!)
        if (equesPres == null) {
            equesPres = EquesPreference(mContext!!)
        }
        val userName = userName
        return network && !StringUtils.isBlank(userName)
    }

    /**
     * 初始化ICVSS
     */
    fun initIcvss() {
        if (messageResponse == null) {
            messageResponse = ServerMessageResponse(context, this@DoorBellService)
        }
        icvss = getInstance(messageResponse!!, MyIOTListener())!!.icvss
    }

    /**
     * 用于接受底层传递出来的视频交互数据，及视频数据
     */
    private inner class MyIOTListener : IOTListener {
        override fun onChannelCreated(channelId: Int, width: Int, height: Int) {
            // 主动视频会话时，把创建成功的通道ID传递给上层
            ELog.d(TAG, " IOT onChannelCreated()... ")
        }

        override fun onChannelClosed(channelId: Int) {
            EventBus.getDefault().post(EventTotalThread(234))
        }

        override fun onStartMedia(
            devId: String,
            channelId: Int,
            width: Int,
            height: Int,
            opType: Int
        ) {
            ELog.d(
                TAG,
                "门铃消息内容变动"
            )
            val bool: Boolean = isShowInComingNotify()
            ELog.d(
                TAG,
                " isShowInComingNotify...$bool "
            )
            if (bool) {
                ELog.d(
                    TAG,
                    " pushMsgReceiver() ，门铃界面拦截，有其它门铃或视频响应中 DoorService...$channelId "
                )
                EventBus.getDefault().post(EventTotalThread(235, channelId, devId))
                return
            } else {
                val intent: Intent = Intent("com.eques.demo.IncomingActivity")
                intent.putExtra("opType", opType)
                intent.setPackage(packageName)
                intent.putExtra("devId", devId)
                intent.putExtra("channelId", channelId)
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }

        }

        override fun onChannelIdUpdate(channelId: Int, width: Int, height: Int) {
            // 收到对端来的呼叫消息，建立通道成功后通知上层更新通道id 根据视频高宽来确认通道
            EventBus.getDefault().post(EventTotalThread(235, channelId))
        }

        override fun onSessionIsExists() {
            ELog.d(TAG, " IOT onSessionIsExists()... ")
        }

        override fun onVideoData(data: ByteArray, len: Int) {
            ELog.d(TAG, " IOT onVideoData()... ")
        }

        override fun onAudioData(data: ByteArray, len: Int) {
            ELog.d(TAG, " IOT onAudioData()... ")
        }

        override fun onBitmap(o: Any) {
            if (imgDataListener != null) {
                imgDataListener!!.bitmapData(o as Bitmap)
            }
        }

        override fun onVideoDataPlaying() {
            if (imgDataListener != null) {
                imgDataListener!!.firFrameCome()
            }
        }

        override fun onVideoHasAnswer() {
            Log.d(TAG, "onVideoHasAnswer...")
        }

        override fun onFps(p0: String?, p1: Int) {
        }

        override fun onLoss(p0: String?, p1: Int) {
        }

        override fun hasRecAnswer() {
        }

        override fun onImgData(devId: String, type: Int, bytes: ByteArray, len: Int) {
//            ELog.e(TAG, " onImgData() devId: ", devId, " type: ", type, " len: ", len);
            if (len > 0) {
//                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, len);
                if (imgDataListener != null) {
                    imgDataListener!!.imgData(bytes, len)
                }
            } else {
                ELog.e(TAG, " 数据流长度返回失败... ")
            }
        }
    }

    /**
     * 判断是否弹出来电通知
     */
    fun isShowInComingNotify(): Boolean {
        ELog.i(TAG, "isShowInComingNotify start...")
        // 检查上下文是否为空，避免空指针异常
        val context = AppUtils.context ?: run {
            ELog.e(TAG, "Context is null, cannot proceed.")
            return false
        }

        // 封装活动前台检测逻辑
        val isActivityForeground: Boolean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            listOf(
                "com.eques.demo.VideoCallActivity",
                "com.eques.demo.IncomingActivity",
                "com.eques.demo.anim.AnimalActivity"
            ).any { isForeground(context, it) }
        } else {
            // 为低版本 Android 提供默认实现
            false
        }

        if (isActivityForeground) {
            ELog.d(TAG, "Activity foreground intercept...")
            return true
        }

        // 可选：记录日志说明当前没有前台活动
        ELog.i(TAG, "门铃来电、视频、语音界面不存在，接受其它门铃请求...")
        return false
    }

    /**
     * 辅助方法：检查指定活动是否在前台
     */
    private fun isForeground(context: Context, activityName: String): Boolean {
        try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val tasks = activityManager.getRunningTasks(1)
            return tasks.isNotEmpty() && tasks[0].topActivity?.className == activityName
        } catch (e: Exception) {
            ELog.e(TAG, "Error checking if activity is foreground: ${e.message}")
            return false
        }
    }




    /**
     * 登录判断
     * 此函数用于判断是否可以进行登录操作，主要根据最后一次刷新时间来决定
     *
     * @param handlerWhat 消息标识，用于指定处理的消息类型
     */
    fun login(handlerWhat: Int) {
        // 获取当前时间毫秒数
        val newTime = System.currentTimeMillis()
        // 判断当前时间与上次刷新时间的间隔是否达到800毫秒
        if (Math.abs(newTime - lastRefreshTime) >= 800) {
            // 登录开始时的日志记录
            ELog.i(TAG, "DoorBellService, login start...")
            // 如果消息标识大于0，则发送消息
            if (handlerWhat > 0) {
                val msg = Message()
                msg.what = handlerWhat
                mHandler.sendMessage(msg);
            }
            // 更新最后一次刷新时间为当前时间
            lastRefreshTime = newTime
            // 启动新线程执行登录操作的日志记录
            ELog.i(TAG, " DoorBellService new Thread(logoutRunnable).start()... ")
        } else {
            // 时间间隔不足800毫秒时的日志记录，表示登录操作过于频繁
            ELog.i(TAG, " DoorBellService login RefreshTime < 0.1S| return. ")
        }
    }

    /**
     * 用户退出登录
     */
    fun userLogout() {
        Executors.newSingleThreadExecutor().submit { icvss!!.equesUserLogOut() }
    }

    /**
     * 执行登录操作
     *
     * @param serverIp 分发得到的登录ip
     */
    private fun doLogin(serverIp: String?) {
        // 同步代码块，确保线程安全
        synchronized(DoorBellService::class.java) {
            // 检查登录状态
            if (loginCheck()) {
                // 获取用户名和密码
                val userName = equesPres?.getString(Config.EQUES_USER_NAME)
                var key = equesPres?.getString(Config.EQUES_USER_KEY, "")
                if (userName == Config.TESTNAME) {
                    key = Config.TESTKEY
                }
                Log.e(TAG, "===$userName")
                Log.e(TAG, "===$key")
                // 调用登录接口
                icvss!!.equesLocalLoginV2(
                    context,
                    userName,
                    key,
                    serverIp,
                    "oauth",
                    "passwd_md5",
                    Config.THIRD_APP_SECRET,
                    Config.THIRD_SERVER_APPID,
                    "",
                    "",
                    HttpsUtils.getSslSocketFactory(),true
                )
            } else {
                // 登录检查失败时的处理
                ELog.d(TAG, " doLogin() tabUserLoginSp is null... ")
                // 以下代码被注释掉，可能是为了调试或备用
                // serverIp = "115.29.49.68";
            }
        }
    }

    /**
     * 根据不同登录场景 进行相关操作
     */
    fun loginScene(loginScene: Int) {
        // 主动登录 自动登录 点击重连
        // 主动登录 自动登录 需要获取设备列表和设备详情的数据
        // 点击重连 不需要获取设备详情 只需要获取设备列表
        val serverIp = equesPres!!.getMainUrl()
        if (isBlank(serverIp)) {
            ELog.d(TAG, " loginScene() serverIp is null... ")
            return
        }
        // 是否是点击重连
        val isClickReconnection = loginScene == MSG_ONCLICK_LOGIN
        // 点击重连
        this.isClickReconnection = isClickReconnection
        // 开始登录
        doLogin(serverIp)
    }

    override fun onDestroy() {
        super.onDestroy()
        ELog.d("DoorBellService onStartCommand:", " onDestroy() start... ")
        unBindReleaseRes()
    }

    /**
     * 服务启动
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @SuppressLint("ForegroundServiceType")
    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        //mContext = AppUtils.getContext();
        //flags = START_STICKY;
        var flags = flags
        startForeground(1, Notification())
        flags = START_FLAG_REDELIVERY
        //flags = START_FLAG_RETRY;
        ELog.d(
            "DoorBellService onStartCommand:",
            String.format(
                Locale.getDefault(),
                "onStartCommand. flags: %d, startId: %d",
                flags,
                startId
            )
        )
        return START_STICKY
        //return super.onStartCommand(intent, flags, startId);
    }

    private var doorBellBinder: DoorBellBinder? = null

    /**
     * 绑定服务
     *
     * @param intent
     * @return
     */
    override fun onBind(intent: Intent): IBinder? {
        if (doorBellBinder == null) {
            doorBellBinder = DoorBellBinder()
        }
        return doorBellBinder
    }

    inner class DoorBellBinder : Binder() {
        val service: DoorBellService
            get() = this@DoorBellService
    }

    override fun unbindService(conn: ServiceConnection) {
        super.unbindService(conn)
        ELog.d("DoorBellService onStartCommand:", " unbindService() start... ")
        unBindReleaseRes()
    }

    /**
     * 解绑后，释放资源
     */
    fun unBindReleaseRes() {
        ELog.d("DoorBellService onStartCommand:", " unBindReleaseRes() start... ")
        isClickReconnection = false
        stopSelf() //自杀服务
    }

    /**
     * 获取当前登录用户名
     */
    var userName: String? = null
        get() {
            // hgz
            field = equesPres!!.getString(Config.EQUES_USER_NAME)
            return field
        }
        private set

    /**
     * 是否主动触发登录（点击操作）
     *
     * @param code
     */
    var isClickReconnection = false
    fun onCLickReconnectionResult(code: Int) {
        // 点击登录结果返回处理
        isClickReconnection = false
        if (code == ResultCode.SUCCESS) {
        }
    }

    companion object {
        private val TAG = DoorBellService::class.java.simpleName
        var icvss: ICVSSUserInstance? = null

        const val MSG_DO_LOGIN: Int = 25 //主动登录
        const val MSG_AUTO_LOGIN = 26 //自动登录
        const val MSG_ONCLICK_LOGIN = 27 //点击重连

        @SuppressLint("StaticFieldLeak")
        @Volatile
        private var instance: DoorBellService? = null

        fun getServiceInstance(): DoorBellService? {
            if (instance == null) {
                synchronized(DoorBellService::class.java) {
                    if (instance == null) {
                        instance = DoorBellService()
                    }
                }
            }
            return instance
        }

        /**
         * 自动登录
         */
        private var lastRefreshTime: Long = 0
    }

    private var imgDataListener: ImgDataListener? = null

    fun setImgDataListener(listener: ImgDataListener?) {
        imgDataListener = listener
    }

}